import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';
import get from '@dfeidao/atom-web/local/get';
import set from '@dfeidao/atom-web/local/set';
// import render_tpl from '@dfeidao/atom-web/render/data-render';
// import { fromString, place, Position, remove } from '@dfeidao/core/dom';
// import { IHandle } from '@dfeidao/core/on';
import render from '@dfeidao/atom-web/render/render';

import a015 from './a015';
import P01 from './P01';
interface Aa {
	param: HTMLElement;
}
interface Bb {
	param: HTMLElement;
}
interface Cc {
	field_name: string;
	field_value: string;
	field: string;
	order_key: string;
}

export default async function a018(fd: IFeidaoAiBrowserComponent, args: { currentTarget: HTMLElement }) {
	const name2title = get(fd, 'name2title');

	//  确定按钮(text)
	const field = args.currentTarget.dataset.feidaoId;
	const check_input = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id=check_' + field + ']');

	const q = {};
	if (check_input.checked) {
		q[field] = ''; // 空条件
	} else {
		const input_node = fd.data.node.querySelector<HTMLInputElement>('[data-feidao-id=input_' + field + ']');
		const v = input_node.value;
		if (v) {
			q[field] = v;
		} else {
			q[field] = '';
		}
		input_node.value = "";
	}

	const condition_node = get(fd, 'condition_node') as Aa;
	const condition_evt = get(fd, 'condition_evt') as Bb;
	const criteria = get(fd, 'criteria') as Bb;
	// console.log('--------a018---------');
	// console.log(condition_node)
	// 渲染条件
	if (condition_node.param[field]) {
		delete condition_node.param[field];
		// (condition_evt.param[field][0]).destroy();
		delete condition_evt.param[field];
		const r_node = fd.data.node.querySelector("#condition_" + field);
		// remove(r_node);
		r_node.parentNode.removeChild(r_node);	// 找到要删除的子元素，然后使用其 parentNode 属性来找到父元素：
	}
	const tpl_d = {} as Cc;
	tpl_d.field = field;
	tpl_d.field_name = name2title[field];
	tpl_d.field_value = q[field] || '空';

	// const tpl_str = render_tpl(tpl_d, P01);

	// const node = fd.data.node.querySelector('[data-feidao-presentation="P01"]');
	// place(fromString(tpl_str), Position.LastIn, node);
	render(fd, tpl_d, P01, 'P01', 'lastin');

	condition_node.param[field] = fd.data.node.querySelector('[data-feidao-id=' + field + ']');
	// condition_evt.param[field] = fd.parse_event(condition_node.param[field]);

	// 刷新列表
	if (check_input.checked) {
		criteria[field] = ''; // 空条件
	} else {
		criteria[field] = (() => {
			if (q[field] === '') {
				// delete criteria[field];
				return '';
			} else {
				return { $like: `%${q[field]}%` };
			}
		})();
	}

	set(fd, 'page_no', 1);
	set(fd, 'criteria', criteria);
	set(fd, 'condition_node', condition_node);
	set(fd, 'condition_evt', condition_evt);
	// console.log(get(fd, 'page_no'), '
	await a015(fd);
}
